const { post, upload } = require('../../utils/request');

Page({
  data: {
    title: '',
    content: '',
    calories: '',
    images: [],
    // 食谱信息
    recipeName: '',
    description: '',
    ingredients: '',
    steps: '',
    cookingTime: '',
    difficultyIndex: null,
    difficulties: ['简单', '中等', '困难'],
    category: '',
    nutrition: {
      protein: '',
      carbs: '',
      fat: '',
      fiber: ''
    },
    tags: '',
    isFormValid: false
  },

  onLoad() {
    this.checkFormValid();
  },

  // 标题输入
  onTitleInput(e) {
    this.setData({
      title: e.detail.value
    });
    this.checkFormValid();
  },

  // 内容输入
  onContentInput(e) {
    this.setData({
      content: e.detail.value
    });
    this.checkFormValid();
  },

  // 卡路里输入
  onCaloriesInput(e) {
    this.setData({
      calories: e.detail.value
    });
    this.checkFormValid();
  },

  // 食谱名称输入
  onRecipeNameInput(e) {
    this.setData({
      recipeName: e.detail.value
    });
  },

  // 食谱描述输入
  onDescriptionInput(e) {
    this.setData({
      description: e.detail.value
    });
  },

  // 食材清单输入
  onIngredientsInput(e) {
    this.setData({
      ingredients: e.detail.value
    });
  },

  // 制作步骤输入
  onStepsInput(e) {
    this.setData({
      steps: e.detail.value
    });
  },

  // 烹饪时间输入
  onCookingTimeInput(e) {
    this.setData({
      cookingTime: e.detail.value
    });
  },

  // 难度选择
  onDifficultyChange(e) {
    this.setData({
      difficultyIndex: e.detail.value
    });
  },

  // 分类输入
  onCategoryInput(e) {
    this.setData({
      category: e.detail.value
    });
  },

  // 营养信息输入
  onProteinInput(e) {
    this.setData({
      'nutrition.protein': e.detail.value
    });
  },

  onCarbsInput(e) {
    this.setData({
      'nutrition.carbs': e.detail.value
    });
  },

  onFatInput(e) {
    this.setData({
      'nutrition.fat': e.detail.value
    });
  },

  onFiberInput(e) {
    this.setData({
      'nutrition.fiber': e.detail.value
    });
  },

  // 标签输入
  onTagsInput(e) {
    this.setData({
      tags: e.detail.value
    });
  },

  // 选择图片
  async chooseImage() {
    try {
      const res = await wx.chooseMedia({
        count: 9 - this.data.images.length,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        sizeType: ['compressed']
      });

      wx.showLoading({
        title: '上传中...'
      });

      const uploadTasks = res.tempFiles.map(file => this.uploadImage(file.tempFilePath));
      const uploadedImages = await Promise.all(uploadTasks);

      this.setData({
        images: [...this.data.images, ...uploadedImages]
      });

      this.checkFormValid();
    } catch (error) {
      console.error('选择图片失败:', error);
      wx.showToast({
        title: '选择图片失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 上传图片
  async uploadImage(tempFilePath) {
    try {
      const res = await upload('/upload/image', tempFilePath, 'image');
      return res.url;
    } catch (error) {
      console.error('上传图片失败:', error);
      throw error;
    }
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.images];
    images.splice(index, 1);
    this.setData({ images });
    this.checkFormValid();
  },

  // 检查表单是否有效
  checkFormValid() {
    const { title, content, calories, images } = this.data;
    const isFormValid = title.trim() && content.trim() && calories && images.length > 0;
    this.setData({ isFormValid });
  },

  // 提交表单
  async handleSubmit() {
    if (!this.data.isFormValid) return;

    wx.showLoading({
      title: '发布中...'
    });

    try {
      const { 
        title, content, calories, images, 
        recipeName, description, ingredients, steps,
        cookingTime, difficultyIndex, category,
        nutrition, tags
      } = this.data;
      
      // 发布社区帖子
      const postResult = await post('/community/posts', {
        title,
        content,
        calories: parseFloat(calories),
        images
      });

      // 如果填写了食谱信息,则保存到食谱数据表
      if (recipeName) {
        await post('/recipes', {
          name: recipeName,
          description,
          image: images[0], // 使用第一张图片作为食谱封面
          ingredients: ingredients.split('\n'), // 将输入文本转换为数组
          steps: steps.split('\n'), // 将输入文本转换为数组
          cookingTime: parseInt(cookingTime) || 0,
          difficulty: this.data.difficulties[difficultyIndex] || '简单',
          category,
          nutrition: {
            calories: parseFloat(calories),
            protein: parseFloat(nutrition.protein) || 0,
            carbs: parseFloat(nutrition.carbs) || 0,
            fat: parseFloat(nutrition.fat) || 0,
            fiber: parseFloat(nutrition.fiber) || 0
          },
          tags: tags.split(',').map(tag => tag.trim()).filter(tag => tag), // 将标签文本转换为数组
          postId: postResult.id // 关联社区帖子ID
        });
      }

      wx.showToast({
        title: '发布成功',
        icon: 'success'
      });

      // 返回上一页并刷新列表
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      if (prevPage) {
        prevPage.onPullDownRefresh();
      }
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);

    } catch (error) {
      console.error('发布失败:', error);
      wx.showToast({
        title: '发布失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  }
}); 